<?php

namespace app\controllers;

use yii\data\Pagination;
use yii\db\Query;
use yii\web\Controller;


class IndustryController extends AdminBaseController {

      //行业列表
     public function actionIndex(){
         $query=(new Query())->select('*')->from('yii_industry')->orderBy('sort');
         $pages=new Pagination(['totalCount' =>$query->count()]);
         $pages->defaultPageSize = 10;//每页10条
         $list=$query->offset($pages->offset)->limit($pages->limit)->all();
         return $this->render('index',['list'=>$list,'pages'=>$pages]);
       }

    //添加
    public function actionAdd(){
        if (\Yii::$app->request->isPost){
            $data=\Yii::$app->request->post();
            $res=\Yii::$app->db->createCommand()->insert('yii_industry',$data)->execute();
            if ($res){
                return json_encode(['code'=>1,'msg'=>'添加成功']);
            }else{
                return json_encode(['code'=>0,'msg'=>'添加失败']);
            }
        }
        return $this->render('add');
    }

    //编辑
    public function actionEdit(){
        if (\Yii::$app->request->isPost){
            $data=\Yii::$app->request->post();;
            $res=\Yii::$app->db->createCommand()->update('yii_industry',$data,array('id'=>$data['id']))->execute();
            if ($res){
                return json_encode(['code'=>1,'msg'=>'更新成功']);
            }else{
                return json_encode(['code'=>0,'msg'=>'无数据更新']);
            }
        }else{
            $id=(int)\Yii::$app->request->get()['id'];
            $list=(new Query())->select('*')->from('yii_industry')->where(array('id'=>$id))->one();
        }

        return $this->render('edit',['list'=>$list]);
    }

    //删除
    public function actionDel(){
        $id=(int)\Yii::$app->request->post()['id'];
        $check=(new Query())->from('yii_company')->where(array('industry'=>$id))->exists();
        if ($check){
            return json_encode(['code'=>0,'msg'=>'无法删除，该行业下存在企业']);
        }
        $res=\Yii::$app->db->createCommand()->delete('yii_industry',array('id'=>$id))->execute();
        if ($res){
            return json_encode(['code'=>1,'msg'=>'删除成功']);
        }else{
            return json_encode(['code'=>0,'msg'=>'删除失败']);
        }
    }


}
